/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author martin
 */
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;
    protected EntityManagerFactory factory = Persistence.createEntityManagerFactory("RestPointPressePU");
    protected EntityManager entityManager = factory.createEntityManager();
    protected EntityTransaction transaction = entityManager.getTransaction();
    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        transaction.begin();
        getEntityManager().persist(entity);
        transaction.commit();
        
    }

    public void edit(T entity) {
        transaction.begin();
        getEntityManager().merge(entity);
        transaction.commit();
    }

    public void remove(T entity) {
        transaction.begin();
        getEntityManager().remove(entityManager.merge(entity));
        transaction.commit();
    }

    public T find(Object id) {
        return entityManager.find(entityClass, id);
        //return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return entityManager.createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = entityManager.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(entityManager.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = entityManager.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }   
}